<template>
  <div class="app-container">
    <el-dialog title="新增/编辑"
               :close-on-click-modal=false
               :visible.sync="dialogVisible">

      <el-tree :props="defaultProps"
               ref="tree"
               :data="tree"
               :default-checked-keys="detaultCheck"
               node-key="Id"
               check-strictly="true"
               show-checkbox
               :default-expand-all="true"
               v-loading="formLoading">
      </el-tree>

      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   :loading="formLoading"
                   @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { load, update, permission, save } from '@/api/sys/role'

export default {
  name: 'update-dialog',
  data () {
    return {
      loading: false,
      formLabelWidth: '120px',
      dialogVisible: false,
      formLoading: true,

      id: '',
      tree: [],
      detaultCheck: [],
      defaultProps: {
        label: 'Title',
        children: 'Items'
      },
    }
  },
  methods: {
    submit () {
      let that = this
      let tree = this.$refs.tree
      let checked_node = tree.getCheckedNodes(false, true)
      let checked_key = checked_node.map(obj => { return obj.Id })
      that.formLoading = true
      save(that.id, checked_key).then(response => {
        // 成功消息
        this.$message({
          message: '更新成功',
          type: 'success'
        })
        that.dialogVisible = false
        that.formLoading = true
      })
    },
    open (id) {
      let that = this
      that.dialogVisible = true
      that.formLoading = true
      that.id = id
      permission(id).then(response => {
        let { Data } = response
        that.tree = Data.Menu
        that.detaultCheck = Data.Checked
        that.formLoading = false
      })
    }
  }
}
</script>
